package com.ruicar.afs.cloud.common.voucher.processor;

import com.alibaba.fastjson.JSONObject;
import com.ruicar.afs.cloud.common.config.VoucherConstant;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.voucher.processor.enums.VoucherMsgType;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public abstract class AbsBaseProcessor <ReqMsg extends AbsBaseRequestMsg, RspMsg extends AbsBaseResponseMsg> {
    /**
     * 获取交易名称
     * @return
     */
    public abstract VoucherMsgType msgType();

    /**
     * 获取交易名称
     * @return
     */
    public abstract List process(ReqMsg request);

    /**
     * 获取请求参数
     * @param request
     * @return
     */
    public abstract IRequest getRequestParams(ReqMsg request) ;
    /**
     * 处理返回结果
     * @param jsonObject
     */
    public abstract RspMsg processRsp(JSONObject jsonObject);
    /**
     * 发送凭证
     * @param iRequest
     */
    public abstract JSONObject send(IRequest iRequest);


    public RspMsg callServer(ReqMsg request) {
        /**
         * 检测开关是否关闭
         */
        if (!VoucherConstant.isOpenFlg()) {
            throw new AfsBaseException("接口开关关闭，不能处理!");
        }
        RspMsg ret = null;
        long start = System.currentTimeMillis();
        log.info("*************start  txn [" +  msgType() + "][" + start + "]**************");
        try {
            IRequest requestParams = this.getRequestParams(request);
            log.info("request message:" + requestParams.getData().toString());
            JSONObject jsonObject = null;
            switch (msgType()) {
                //推送凭证信息
                case CONFIDENTIAL_INFORMATION:
                    jsonObject =  this.send(requestParams);
                    break;
                case AUXILIARY_ACCOUNT:
                    jsonObject = this.send(requestParams);
                    break;
                default:
                    log.error("凭证方法未实现"+AfsEnumUtil.desc(msgType()));
                    throw new AfsBaseException("not support now");
            }
            log.info("***********发送凭证报文response："+jsonObject+"***************");
            ret = this.processRsp(jsonObject);
        } catch (Exception e) {
            log.error("调用凭证服务[" + this.msgType() + "]异常：" + e.getMessage(), e);
            throw new AfsBaseException("调用凭证服务[" + this.msgType() + "]异常：" + e.getMessage());
        }
        return ret;
    }
}
